﻿using System;
using System.IO;

namespace BoilerEventAppl {
    // Boiler 类
    class Boiler {
        public int Temp { get; private set; }
        public int Pressure { get; private set; }

        public Boiler(int temp, int pressure) {
            Temp = temp;
            Pressure = pressure;
        }
    }

    // 事件发布器
    class DelegateBoilerEvent {
        //委托
        public delegate void BoilerLogHandler(string status);

        // 基于上面的委托定义事件
        public event BoilerLogHandler BoilerEventLog;

        public void LogProcess() {
            string remarks = "O.K.";
            Boiler boiler = new Boiler(100, 12);
            int temp = boiler.Temp;
            int pressure = boiler.Pressure;

            if (temp > 150 || temp < 80 || pressure < 12 || pressure > 15) {
                remarks = "Need Maintenance";
            }
            //触发事件
            OnBoilerEventLog($"Logging Info:\nTemperature: {temp}\nPressure: {pressure}\nMessage: {remarks}");
        }
        //执行事件

        protected void OnBoilerEventLog(string message) {
            BoilerEventLog?.Invoke(message);
        }
    }

    // 该类保留写入日志文件的条款
    class BoilerInfoLogger : IDisposable {
        private readonly StreamWriter _streamWriter;

        public BoilerInfoLogger(string filename) {
            _streamWriter = new StreamWriter(new FileStream(filename, FileMode.Append, FileAccess.Write));
        }

        public void Logger(string info) {
            _streamWriter.WriteLine(info);
            Console.WriteLine("=======写入了日志=======");
        }

        public void Dispose() {
            _streamWriter?.Close();
        }
    }

    // 事件订阅器
    public class RecordBoilerInfo {
        static void Logger(string info) {
            Console.WriteLine(info);
        }

        static void Main(string[] args) {
            using (BoilerInfoLogger fileLogger = new BoilerInfoLogger("F:\\c#\\boiler.txt")) {
                //创建 DelegateBoilerEvent 对象，该对象用于发布 事件
                DelegateBoilerEvent boilerEvent = new DelegateBoilerEvent();
                //通过+=操作符，将两个事件处理方法（Logger和fileLogger.Logger）订阅到BoilerEventLog事件上
                //订阅事件是指 boilerEvent.BoilerEventLog 去订阅 Logger 这个方法
                boilerEvent.BoilerEventLog += Logger;
                boilerEvent.BoilerEventLog += fileLogger.Logger;
                //触发事件
                boilerEvent.LogProcess();
            }

            Console.ReadLine();
        }
    }
}